import qs from 'qs'
import md5 from 'js-md5'
import store from '../store'

require('es6-promise').polyfill()

// 请求的拦截器
function GetQueryString (name) {
  var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)')
  var r = window.location.search.substr(1).match(reg)
  if (r != null) {
    return unescape(r[2])
  }
  return null
}

function getSdkVersion () {
  if (window.huo) {//SDK
    if (window.huo.getSdkVersion) {
      return window.huo.getSdkVersion()
    }
    return 'V1.0.1'
  }
  if (window.micro) {//微端
    if (window.micro.getSdkVersion) {
      return window.micro.getSdkVersion() + '.m'
    }
    return 'V1.0.1.m'
  }
  //H5
  return 'V1.0.1.h'
}

axios.interceptors.request.use(function (config) {
  store.commit('UPDATE_LOADING_STATUS', {isLoading: true})

  let token = ''
  let appId = 0
  let clientId = ''
  let device_id = ''
  let error = ''
  if (window.huo) {
    try {
      token = window.localStorage.getItem('app-float-token') || window.huo && window.huo.getToken() || window.huo && window.huo.getToken('') || getUrlParams('token')
    } catch (e) {
      error = e.toString()
    }
    try {
      appId = window.huo.getAppId()
    } catch (e) {
      error += e.toString() + ';'
    }
    try {
      clientId = window.huo.getClientId()
    } catch (e) {
      error += e.toString() + ';'
    }
    try {
      device_id = window.huo.getDeviceId()
    } catch (e) {
      error += e.toString() + ';'
    }
  } else {
    //  此种情况为H5浮点使用iframe加载此页面所需要用的到token，appid
    if (process.env.NODE_ENV !== 'development') {
      token = GetQueryString('token') || localStorage.getItem('token')
      appId = GetQueryString('appId') || localStorage.getItem('appId')
      if (!!token && !!appId) {
        localStorage.setItem('token', token)
        localStorage.setItem('appId', appId)
      }
    }
  }
  if (process.env.NODE_ENV === 'development') {
    appId = 108
    token = 'c3b46daaf5bd160a1d4cb958650bfbfe'
  }
  let sdkVersion = store.state.sdkVersion
  if (!sdkVersion) {
    sdkVersion = getSdkVersion()
    store.commit('UPDATE_SDK_VERSION', sdkVersion)
  }
  let options = {
    'ts': new Date().getTime(),
    'app_id': appId,
    'client_id': clientId,
    'token': token,
    'game-pkg_name': '',
    'game-app_ver': '',
    'game-h_ver': '',
    'game-sdk_ver': sdkVersion,
    'agent-ch': 0,
    'agent-sub_ch': '',
    'device-device_id': device_id,
    'device-mac': '',
    'device-ip': '',
    'device-brand': '',
    'device-model': '',
    'device-os': '',
    'device-os_version': '',
    'device-screen': window.screen.width * window.devicePixelRatio + 'x' + window.screen.height * window.devicePixelRatio,
    'device-net': '',
    'device-imsi': '',
    'format': 'json',
  }
  if (error) {
    options['crash-msg'] = error
  }
  // 判断请求的类型
  // 如果是post请求就把默认参数拼到data里面
  // 如果是get请求就拼到params里面
  if (config.method === 'post') {
    let oldData = qs.parse(config.data)

    let newData = {
      ...options,
      ...oldData
    }
    let keys = Object.keys(newData).sort()
    let data = {}
    let str = ''
    keys.forEach(key => {
      data[key] = newData[key]
      str += '&' + key + '=' + newData[key]
    })
    let newUrl = ''
    if (config.url.indexOf(window.apiUrl) !== -1) {
      newUrl = config.url.replace(`${window.apiUrl}/`, '')
    } else if (config.url.substr(1).indexOf('testapi') !== -1) {
      newUrl = config.url.substr(1).replace('testapi/', '')
    }
    let sign = ('POST&' + encodeURIComponent(newUrl) + '&' + encodeURIComponent(str.substr(1)) + '&' + token).replace(/\(/g, '%28').replace(/\)/g, '%29')
    data.sign = md5(sign)

    config.data = qs.stringify(data)
  } else if (config.method === 'get') {
    let newData = {
      ...options,
      ...config.params
    }
    let keys = Object.keys(newData).sort()
    let data = {}
    let str = ''
    keys.forEach(key => {
      data[key] = newData[key]
      str += '&' + key + '=' + newData[key]
    })
    let newUrl = ''
    if (config.url.indexOf(window.apiUrl) !== -1) {
      newUrl = config.url.replace(`${window.apiUrl}/`, '')
    } else if (config.url.substr(1).indexOf('testapi') !== -1) {
      newUrl = config.url.substr(1).replace('testapi/', '')
    }
    let sign = ('GET&' + encodeURIComponent(newUrl) + '&' + encodeURIComponent(str.substr(1)) + '&' + token).replace(/\(/g, '%28').replace(/\)/g, '%29')
    data.sign = md5(sign)

    config.params = data
  }

  return config
}, function (error) {
  return Promise.reject(error)
})

// 响应的拦截器
axios.interceptors.response.use(function (response) {
  store.commit('UPDATE_LOADING_STATUS', {isLoading: false})

  let {data} = response
  if (data.code === 200) {
    if (data.data && data.data.user_token) {
      window.localStorage.setItem('app-float-token', data.data.user_token)
    }
  } else if (data.code === 1002) {
    window.localStorage.removeItem('app-float-token')
  }
  // 对响应数据做点什么
  return response
}, function (error) {
  // 对响应错误做点什么
  return Promise.reject(error)
})

let testapi = process.env.NODE_ENV === 'development' ? '/testapi' : window.apiUrl
let localapi = process.env.NODE_ENV === 'development' ? '/localapi' : window.apiUrl

// 发送短信
// http://doc.1tsdk.com/138?page_id=2911
export const smsSend = (params, succ, fail) => {
  axios.post(`${testapi}/v8/sms/send`, params).then(({data}) => {
    if (data.code === 200) {
      succ(data.msg)
    } else {
      fail(data.msg)
    }
  }).catch(error => {
    console.info(error)
    fail()
  })
}

// 获取浮点基础信息
// http://doc.1tsdk.com/138?page_id=3410
export const getBaseInfo = (succ, fail) => {
  let timeOut = setTimeout(() => {
    axios.post(`${testapi}/cfloat/base/info`).then(({data}) => {
      if (data.code === 200) {
        for (let i = 0; i < data.data.entrance.length; i++) {
          if (data.data.entrance[i].code == 'cpl') {
            // router.replace({path:'/cpl'})
          }
        }
        succ(data.data)
        clearTimeout(timeOut)
      } else {
        fail(data.msg)
        clearTimeout(timeOut)
      }
    }).catch(error => {
      console.info(error)
      fail()
    })
  }, 1000)
}

// 用户信息
// http://doc.1tsdk.com/138?page_id=3273
export const getUserDetail = (succ, fail) => {
  let timeOut = setTimeout(() => {
    axios.get(`${testapi}/cfloat/user/index`).then(({data}) => {
      if (data.code === 200) {
        succ(data.data)
        clearTimeout(timeOut)
      } else {
        fail(data.msg)
        clearTimeout(timeOut)
      }
    }).catch(error => {
      console.info(error)
      fail()
    })
  }, 1000)
}

// 修改用户密码
// http://doc.1tsdk.com/138?page_id=3373
export const updateUserPasswd = (data, succ, fail) => {
  axios.post(`${testapi}/cfloat/user/passwd/update`, data).then(({data}) => {
    if (data.code === 200) {
      succ(data.data)
    } else {
      fail(data.msg)
    }
  }).catch(error => {
    console.info(error)
    fail()
  })
}

// 礼包列表
// http://doc.1tsdk.com/138?page_id=3276
export const getGiftList = (params, succ, fail) => {
  axios.get(`${testapi}/cfloat/gift/list`, {params}).then(({data}) => {
    if (data.code === 200) {
      succ(data.data)
    } else {
      fail(data.msg)
    }
  }).catch(error => {
    console.info(error)
    fail()
  })
}

// 礼包详情页
// http://doc.1tsdk.com/138?page_id=3277
export const getGiftDetail = (id, succ, fail) => {
  axios.get(`${testapi}/cfloat/gift/detail`, {
    params: {
      gift_id: id
    }
  }).then(({data}) => {
    if (data.code === 200) {
      succ(data.data)
    } else {
      fail(data.msg)
    }
  }).catch(error => {
    console.info(error)
    fail()
  })
}

// 礼包领取
// http://doc.1tsdk.com/138?page_id=3278
export const addGift = (id, succ, fail) => {
  axios.post(`${testapi}/cfloat/user/gift/add`, {
    gift_id: id
  }).then(({data}) => {
    if (data.code === 200) {
      succ(data.data)
    } else {
      fail(data.msg)
    }
  }).catch(error => {
    console.info(error)
    fail()
  })
}

export const getServiceUploadInfo = (succ, fail) => {
  axios.post(`${testapi}/v9/custom/upload`).then(({data}) => {
    if (data.code === 200) {
      succ(data.data)
    } else {
      fail(data.msg)
    }
  }).catch(error => {
    fail()
  })
}

// 资讯列表
// http://doc.1tsdk.com/138?page_id=3281
export const getNewsList = (params, succ, fail) => {
  axios.get(`${testapi}/cfloat/news/list`, {params}).then(({data}) => {
    if (data.code === 200) {
      succ(data.data)
    } else {
      fail(data.msg)
    }
  }).catch(error => {
    console.info(error)
    fail()
  })
}

// 资讯详情
// http://doc.1tsdk.com/138?page_id=3282
export const getNewsDetail = (id, succ, fail) => {
  axios.get(`${testapi}/cfloat/news/detail`, {
    params: {
      news_id: id
    }
  }).then(({data}) => {
    if (data.code === 200) {
      succ(data.data)
    } else {
      fail(data.msg)
    }
  }).catch(error => {
    console.info(error)
    fail()
  })
}

// 消息列表
// http://doc.1tsdk.com/138?page_id=3370
export const getMsgList = (params, succ, fail) => {
  axios.get(`${testapi}/cfloat/msg/list`, {params}).then(({data}) => {
    if (data.code === 200) {
      succ(data.data)
    } else {
      fail(data.msg)
    }
  }).catch(error => {
    console.info(error)
    fail()
  })
}

export const gmPayQuery = (data, succ, fail) => {
  axios.post(`${testapi}/cfloat/gamemoney/order/query`, data).then(({data}) => {
    if (data.code === 200) {
      succ(data.data)
    } else {
      fail(data.msg)
    }
  }).catch(error => {
    console.info(error)
    fail('查询失败')
  })
}

// 优惠券列表
// https://doc.huosdk.com/web/#/138?page_id=12862
export const getCouponList = (data, succ, fail) => {
  axios.post(`${testapi}/cfloat/mem/coupon/list`, data).then(({data}) => {
    if (data.code === 200) {
      succ(data.data)
    } else {
      fail(data.msg)
    }
  }).catch(error => {
    console.info(error)
    fail()
  })
}

// 优惠券领取
export const receiveCoupon = (id, succ, fail) => {
  axios.post(`${testapi}/cfloat/mem/coupon/receive`, {
    coupon_id: id
  }).then(({data}) => {
    if (data.code === 200) {
      succ(data.data)
    } else {
      fail(data.msg)
    }
  }).catch(error => {
    console.info(error)
    fail()
  })
}

// 我的优惠券列表
export const getMyCouponList = (data, succ, fail) => {
  axios.post(`${testapi}/cfloat/mem/coupon/myList`, data).then(({data}) => {
    if (data.code === 200) {
      succ(data.data)
    } else {
      fail(data.msg)
    }
  }).catch(error => {
    console.info(error)
    fail()
  })
}

// 获取K金充值记录列表
export const getGmRechargeList = (params, succ, fail) => {
  axios.get(`${testapi}/cfloat/gamemoney/recharge_record`, {params}).then(({data}) => {
    if (data.code === 200) {
      succ(data.data)
    } else {
      fail(data.msg)
    }
  }).catch(error => {
    console.info(error)
    fail()
  })
}

// 游戏充值记录
export const getOrderList = (params, succ, fail) => {
  axios.get(`${testapi}/cfloat/order/list`, {params}).then(({data}) => {
    if (data.code === 200) {
      succ(data.data)
    } else {
      fail(data.msg)
    }
  }).catch(error => {
    console.info(error)
    fail()
  })
}

// K金充值
export const gmRecharge = (succ, fail) => {
  axios.post(`${testapi}/cfloat/gamemoney/recharge`).then(({data}) => {
    if (data.code === 200) {
      succ(data.data)
    } else if (data.code === -1012) {
      fail(false)
    } else {
      fail(data.msg)
    }
  }).catch(error => {
    console.info(error)
    fail()
  })
}

// 选择支付方式进行支付
// http://doc.1tsdk.com/138?page_id=3442
export const gmPayPost = (data, succ, fail) => {
  axios.post(`${testapi}/cfloat/gamemoney/pay/post`, data).then(({data}) => {
    if (data.code === 200) {
      succ(data.data)
    } else {
      fail(data.msg)
    }
  }).catch(error => {
    console.info(error)
    fail()
  })
}

// 实名认证
// http://doc.1tsdk.com/138?page_id=3283
export const setIdentify = (params, succ, fail) => {
  axios.get(`${testapi}/cfloat/identify/set`, {params}).then(({data}) => {
    if (data.code === 200) {
      succ(data)
    } else {
      fail(data.msg)
    }
  }).catch(error => {
    console.info(error)
    fail()
  })
}

// 我的小号列表
// http://doc.1tsdk.com/138?page_id=3395
export const getAccountList = (succ, fail) => {
  axios.post(`${testapi}/sdk/v9/account/list`).then(({data}) => {
    if (data.code === 200) {
      succ(data.data)
    } else {
      fail(data.msg)
    }
  }).catch(error => {
    console.info(error)
    fail()
  })
}

// 添加小号
// http://doc.1tsdk.com/138?page_id=3396
export const addAccount = (nickname, succ, fail) => {
  axios.post(`${testapi}/sdk/v9/account/add`, {
    nickname
  }).then(({data}) => {
    if (data.code === 200) {
      succ(data.msg)
    } else {
      fail(data.msg)
    }
  }).catch(error => {
    console.info(error)
    fail()
  })
}

export const editAccount = (data, succ, fail) => {
  axios.post(`${testapi}/sdk/v9/account/edit`, data).then(({data}) => {
    if (data.code === 200) {
      succ(data.msg)
    } else {
      fail(data.msg)
    }
  }).catch(error => {
    console.info(error)
    fail()
  })
}

// 切换小号
// http://doc.1tsdk.com/138?page_id=3397
export const switchAccount = (id, succ, fail) => {
  axios.post(`${testapi}/sdk/v9/account/change`, {
    mg_mem_id: id
  }).then(({data}) => {
    if (data.code === 200) {
      succ(data.msg)
      // try{window.huo.switchLittleAccount()}catch(t){}
    } else {
      fail(data.msg)
    }
  }).catch(error => {
    console.info(error)
    fail()
  })
}

// 用户密保信息
// http://doc.1tsdk.com/138?page_id=3399
export const bindInfo = (succ, fail) => {
  axios.post(`${testapi}/cfloat/bind/info`).then(({data}) => {
    if (data.code === 200) {
      succ(data.data)
    } else {
      fail(data.msg)
    }
  }).catch(error => {
    console.info(error)
    fail()
  })
}

// 校验原有手机
// http://doc.1tsdk.com/138?page_id=3400
export const smsCheckold = (data, succ, fail) => {
  axios.post(`${testapi}/cfloat/sms/checkold`, data).then(({data}) => {
    if (data.code === 200) {
      succ(data.msg)
    } else {
      fail(data.msg)
    }
  }).catch(error => {
    console.info(error)
    fail()
  })
}

// 绑定手机
// http://doc.1tsdk.com/138?page_id=3401
export const bindMobile = (data, succ, fail) => {
  axios.post(`${testapi}/cfloat/mobile/bind`, data).then(({data}) => {
    if (data.code === 200) {
      succ(data.msg)
    } else {
      fail(data.msg)
    }
  }).catch(error => {
    console.info(error)
    fail()
  })
}

// 发送短信
// http://doc.1tsdk.com/138?page_id=3284
export const fSmsSend = (data, succ, fail) => {
  axios.post(`${testapi}/cfloat/sms/send`, data).then(({data}) => {
    if (data.code === 200) {
      succ(data.msg)
    } else {
      fail(data.msg)
    }
  }).catch(error => {
    console.info(error)
    fail()
  })
}

// 找回密码发送短信
// https://doc.huosdk.com/web/#/232?page_id=12926
export const devSendSms = (data, succ, fail) => {
  axios.post(`${testapi}/password/send_sms`, data).then(({data}) => {
    if (data.code === 200) {
      succ(data.data)
    } else {
      fail(data.msg)
    }
  }).catch(error => {
    console.info(error)
    fail()
  })
}




